package com.laogao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laogao.entity.Question;
import com.laogao.mapper.QuestionMapper;
import com.laogao.service.QuestionService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    private static final int BATCH_SIZE = 1000;

    @Override
    @Async("taskExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 强制新事务
    public CompletableFuture<Void> saveBatchAsync(List<Question> questionList) {
        try {
            // 调用父类的saveBatch方法执行批量插入
            saveBatch(questionList, BATCH_SIZE);
        } catch (Exception e) {
            log.error("批量保存题目失败，原因：", e);
            // 包装为 CompletionException，便于上层捕获
            throw new CompletionException(e);
        }
        return CompletableFuture.completedFuture(null);
    }
}